axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

const tb = document.querySelector('#tb');
const form = document.querySelector('form');

const renderbooks = async() => {
  const {data:res} = await axios.get('/api/getbooks')
    // .then(({ data: res }) => {
    // const { data } = res
  
   const html =  res.data.map((item) => {
      return `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#"data-id="${item.id}">删除</a></td>
    </tr>`
    }).join('')

    tb.innerHTML=html
  // })
}
renderbooks()

form.addEventListener('submit',async function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true})

  const { data:res }= await axios.post('/api/addbook', data)//.then(({ data: res }) => {
  //   alert(res.msg)
  //   if (!res.status === 201) return
  //   this.reset()
  //   renderbooks()
  // })

  alert(res.msg)
    if (!res.status === 201) return
    this.reset()
    renderbooks()
})

tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    let id = e.target.dataset.id
    axios.get('/api/delbook?id=' + id).then(({data:res}) => {
      renderbooks()
    })
    
  }

})
